package com.ruoyi.puyu.service.impl;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.RoleEnum;
import com.ruoyi.common.enums.StudentExpiredTypeEnum;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.puyu.domain.PuyuIntegral;
import com.ruoyi.puyu.domain.PuyuMemberIntegral;
import com.ruoyi.puyu.domain.PuyuStudent;
import com.ruoyi.puyu.mapper.PuyuIntegralMapper;
import com.ruoyi.puyu.mapper.PuyuLessonStudentMapper;
import com.ruoyi.puyu.mapper.PuyuMemberIntegralMapper;
import com.ruoyi.puyu.mapper.PuyuStudentMapper;
import com.ruoyi.puyu.service.IPuyuStudentService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * 学员Service业务层处理
 * 
 * @author wusongwen
 * @date 2024-05-01
 */
@Service
public class PuyuStudentServiceImpl implements IPuyuStudentService 
{
    private static final Logger logger = LoggerFactory.getLogger(PuyuStudentServiceImpl.class);
    @Autowired
    private PuyuStudentMapper puyuStudentMapper;
    @Autowired
    private PuyuLessonStudentMapper puyuLessonStudentMapper;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private PuyuIntegralMapper puyuIntegralMapper;
    @Autowired
    private PuyuMemberIntegralMapper puyuMemberIntegralMapper;

    /**
     * 查询学员
     * 
     * @param studentId 学员主键
     * @return 学员
     */
    @Override
    public PuyuStudent selectPuyuStudentByStudentId(Long studentId)
    {

        int studentLessonCount = puyuLessonStudentMapper.selectPuyuLessonStudentCountByStudentId(studentId);
        PuyuStudent puyuStudent = puyuStudentMapper.selectPuyuStudentByStudentId(studentId);
        puyuStudent.getParams().put("studentLessonCount", studentLessonCount);
        return puyuStudent;
    }

    @Override
    public PuyuStudent selectPuyuStudentByStudentCode(String studentCode) {
        return puyuStudentMapper.selectPuyuStudentByStudentCode(studentCode);
    }

    @Override
    public String selectPuyuStudentCode(String studentCode) {
        PuyuStudent puyuStudent = puyuStudentMapper.selectPuyuStudentCode(studentCode);
        int studentCodeTemp = 0;
        if (null == puyuStudent) {
            studentCodeTemp = Integer.parseInt(studentCode) + 1;
        } else {
            studentCodeTemp = Integer.parseInt(puyuStudent.getStudentCode()) + 1;
        }
        return studentCodeTemp + "";
    }

    /**
     * 查询学员列表
     * 
     * @param puyuStudent 学员
     * @return 学员
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<PuyuStudent> selectPuyuStudentList(PuyuStudent puyuStudent)
    {
        return puyuStudentMapper.selectPuyuStudentList(puyuStudent);
    }

    @Override
    public List<PuyuStudent> selectStudentNameList(String studentName) {
        return puyuStudentMapper.selectStudentNameList(studentName);
    }

    @Override
    public List<Map<String, Object>> selectStudentLessonList(PuyuStudent puyuStudent) {
        return puyuStudentMapper.selectStudentLessonList(puyuStudent);
    }

    @Override
    public List<PuyuStudent> selectStudentTrainingList(PuyuStudent puyuStudent) {
        if ("0".equals(puyuStudent.getParams().get("trainingCountItem"))) {
            return puyuStudentMapper.selectStudentTrainingZeroList(puyuStudent);
        }
        return puyuStudentMapper.selectStudentTrainingList(puyuStudent);
    }

    @Override
    public List<Map<String, Object>> selectStudentStrengthTestList(PuyuStudent puyuStudent) {
        return puyuStudentMapper.selectStudentStrengthTestList(puyuStudent);
    }

    /**
     * 查询学员用户列表
     * @return
     */
    @Override
    public List<Map<String, Object>> selectStudentUserList() {
        return puyuStudentMapper.selectStudentUserList();
    }

    @Override
    public List<Map<String, Object>> selectStudentParentUserList() {
        return puyuStudentMapper.selectStudentParentUserList();
    }

    @Override
    public List<Map<String, Object>> selectStudentList() {
        return puyuStudentMapper.selectStudentList();
    }

    @Override
    public List<Map<String, Object>> listNotExpiredStudents() {
        return puyuStudentMapper.listNotExpiredStudents();
    }

    @Override
    public List<Map<String, Object>> selectTestStudentList() {
        return puyuStudentMapper.selectTestStudentList();
    }

    /**
     * 新增学员
     * 
     * @param puyuStudent 学员
     * @return 结果
     */
    @Override
    @Transactional
    public int insertPuyuStudent(PuyuStudent puyuStudent)
    {
        // 校验学号是否已存在
        PuyuStudent puyuStudentTemp = puyuStudentMapper.selectPuyuStudentByStudentCode(puyuStudent.getStudentCode());
        if (null != puyuStudentTemp) {
            throw new ServiceException(MessageUtils.message("student.already.exists"));
        }
        // 默认学员的deptId为103
        if (null == puyuStudent.getDeptId()) {
            puyuStudent.setDeptId(103L);
        }
        SysUser user = userService.selectUserByPhoneNumber(puyuStudent.getPhone());
        if (null == user) {
            user = new SysUser();
            user.setCreateBy(SecurityUtils.getUsername());
            String password = configService.selectConfigByKey("sys.user.initPassword");
            user.setPassword(SecurityUtils.encryptPassword(password));
            user.setDeptId(puyuStudent.getDeptId());
            user.setUserName(puyuStudent.getPhone());
            user.setNickName(puyuStudent.getStudentName());
            user.setPhonenumber(puyuStudent.getPhone());
            user.setEmail(puyuStudent.getPhone() + "@ptba.cn");
            user.setSex("0");
            user.setStatus("0");
            user.setDelFlag("0");
            Long[] roleIds = new Long[]{RoleEnum.STUDENT.getRoleId()};
            user.setRoleIds(roleIds);
            userService.insertUser(user);
        }
        puyuStudent.setUserId(user.getUserId());
        puyuStudent.setCreateTime(DateUtils.getNowDate());
        // 期限类型处理
        if (StudentExpiredTypeEnum.THREE_MONTHS.getExpiredType().compareTo(puyuStudent.getExpiredType()) == 0) {
            puyuStudent.setExpiredTime(DateUtils.addMonths(puyuStudent.getCreateTime(), 3));
        } else if (StudentExpiredTypeEnum.SIX_MONTHS.getExpiredType().compareTo(puyuStudent.getExpiredType()) == 0) {
            puyuStudent.setExpiredTime(DateUtils.addMonths(puyuStudent.getCreateTime(), 6));
        } else if (StudentExpiredTypeEnum.ONE_YEAR.getExpiredType().compareTo(puyuStudent.getExpiredType()) == 0) {
            puyuStudent.setExpiredTime(DateUtils.addYears(puyuStudent.getCreateTime(), 1));
        } else if (StudentExpiredTypeEnum.TWO_YEARS.getExpiredType().compareTo(puyuStudent.getExpiredType()) == 0) {
            puyuStudent.setExpiredTime(DateUtils.addYears(puyuStudent.getCreateTime(), 2));
        }

        return puyuStudentMapper.insertPuyuStudent(puyuStudent);
    }

    /**
     * 修改学员
     * 
     * @param puyuStudent 学员
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updatePuyuStudent(PuyuStudent puyuStudent)
    {
        PuyuStudent puyuStudentTemp = puyuStudentMapper.selectPuyuStudentByStudentId(puyuStudent.getStudentId());
        // 处理有效期
        handleStudentExpiredTime(puyuStudentTemp, puyuStudent);
        // 处理手机号
        handleStudentPhone(puyuStudentTemp, puyuStudent);
        puyuStudent.setUpdateTime(DateUtils.getNowDate());
        return puyuStudentMapper.updatePuyuStudent(puyuStudent);
    }

    @Override
    public int plusClassUsed(Long studentId) {
        return puyuStudentMapper.plusClassUsed(studentId);
    }

    @Override
    public int subtractClassUsed(Long studentId) {
        return puyuStudentMapper.subtractClassUsed(studentId);
    }

    /**
     * 批量删除学员
     * 
     * @param studentIds 需要删除的学员主键
     * @return 结果
     */
    @Override
    public int deletePuyuStudentByStudentIds(Long[] studentIds)
    {
        return puyuStudentMapper.updatePuyuStudentByStudentIds(studentIds);
    }

    /**
     * 删除学员信息
     * 
     * @param studentId 学员主键
     * @return 结果
     */
    @Override
    public int deletePuyuStudentByStudentId(Long studentId)
    {
        return puyuStudentMapper.deletePuyuStudentByStudentId(studentId);
    }

    /**
     * 处理学员有效期
     * @param puyuStudentTemp 更新前学员信息
     * @param puyuStudent 更新后学员信息
     */
    public void handleStudentExpiredTime(PuyuStudent puyuStudentTemp, PuyuStudent puyuStudent) {
        // 期限类型未改变
        if (puyuStudent.getExpiredType().compareTo(puyuStudentTemp.getExpiredType()) == 0) {
            return;
        }

        // 期限类型变大
        if (puyuStudent.getExpiredType().compareTo(puyuStudentTemp.getExpiredType()) > 0) {
            if (StudentExpiredTypeEnum.TWO_YEARS.getExpiredType().compareTo(puyuStudent.getExpiredType()) == 0) {
                if (StudentExpiredTypeEnum.ONE_YEAR.getExpiredType().compareTo(puyuStudentTemp.getExpiredType()) == 0) {
                    puyuStudent.setExpiredTime(DateUtils.addYears(puyuStudentTemp.getExpiredTime(), 1));
                } else if (StudentExpiredTypeEnum.SIX_MONTHS.getExpiredType().compareTo(puyuStudentTemp.getExpiredType()) == 0) {
                    puyuStudent.setExpiredTime(DateUtils.addMonths(puyuStudentTemp.getExpiredTime(), 18));
                } else if (StudentExpiredTypeEnum.THREE_MONTHS.getExpiredType().compareTo(puyuStudentTemp.getExpiredType()) == 0) {
                    puyuStudent.setExpiredTime(DateUtils.addMonths(puyuStudentTemp.getExpiredTime(), 21));
                }
            } else if (StudentExpiredTypeEnum.ONE_YEAR.getExpiredType().compareTo(puyuStudent.getExpiredType()) == 0) {
                if (StudentExpiredTypeEnum.SIX_MONTHS.getExpiredType().compareTo(puyuStudentTemp.getExpiredType()) == 0) {
                    puyuStudent.setExpiredTime(DateUtils.addMonths(puyuStudentTemp.getExpiredTime(), 6));
                } else if (StudentExpiredTypeEnum.THREE_MONTHS.getExpiredType().compareTo(puyuStudentTemp.getExpiredType()) == 0){
                    puyuStudent.setExpiredTime(DateUtils.addMonths(puyuStudentTemp.getExpiredTime(), 9));
                }
            } else if (StudentExpiredTypeEnum.SIX_MONTHS.getExpiredType().compareTo(puyuStudent.getExpiredType()) == 0) {
                if (StudentExpiredTypeEnum.THREE_MONTHS.getExpiredType().compareTo(puyuStudentTemp.getExpiredType()) == 0) {
                    puyuStudent.setExpiredTime(DateUtils.addMonths(puyuStudentTemp.getExpiredTime(), 3));
               }
            }

            return;
        }

        // 期限类型变小
        if (StudentExpiredTypeEnum.THREE_MONTHS.getExpiredType().compareTo(puyuStudent.getExpiredType()) == 0) {
            if (StudentExpiredTypeEnum.SIX_MONTHS.getExpiredType().compareTo(puyuStudentTemp.getExpiredType()) == 0) {
                puyuStudent.setExpiredTime(DateUtils.addMonths(puyuStudentTemp.getExpiredTime(), -3));
            } else if (StudentExpiredTypeEnum.ONE_YEAR.getExpiredType().compareTo(puyuStudentTemp.getExpiredType()) == 0) {
                puyuStudent.setExpiredTime(DateUtils.addMonths(puyuStudentTemp.getExpiredTime(), -9));
            } else if (StudentExpiredTypeEnum.TWO_YEARS.getExpiredType().compareTo(puyuStudentTemp.getExpiredType()) == 0) {
                puyuStudent.setExpiredTime(DateUtils.addMonths(puyuStudentTemp.getExpiredTime(), -21));
            }
        } else if (StudentExpiredTypeEnum.SIX_MONTHS.getExpiredType().compareTo(puyuStudent.getExpiredType()) == 0) {
            if (StudentExpiredTypeEnum.ONE_YEAR.getExpiredType().compareTo(puyuStudentTemp.getExpiredType()) == 0) {
                puyuStudent.setExpiredTime(DateUtils.addMonths(puyuStudentTemp.getExpiredTime(), -6));
            } else if (StudentExpiredTypeEnum.TWO_YEARS.getExpiredType().compareTo(puyuStudentTemp.getExpiredType()) == 0) {
                puyuStudent.setExpiredTime(DateUtils.addMonths(puyuStudentTemp.getExpiredTime(), -18));
            }
        } else if (StudentExpiredTypeEnum.ONE_YEAR.getExpiredType().compareTo(puyuStudent.getExpiredType()) == 0) {
            if (StudentExpiredTypeEnum.TWO_YEARS.getExpiredType().compareTo(puyuStudentTemp.getExpiredType()) == 0) {
                puyuStudent.setExpiredTime(DateUtils.addYears(puyuStudentTemp.getExpiredTime(), -1));
            }
        }
    }

    /**
     * 处理学员手机号
     * @param puyuStudentTemp 更新前学员信息
     * @param puyuStudent 更新后学员信息
     */
    @Transactional(rollbackFor = Exception.class)
    public void handleStudentPhone(PuyuStudent puyuStudentTemp, PuyuStudent puyuStudent) {
        // 手机号未改变
        if (puyuStudent.getPhone().equals(puyuStudentTemp.getPhone())) {
            return;
        }
        SysUser user = userService.selectUserByPhoneNumber(puyuStudent.getPhone());
        if (null == user) {
            user = new SysUser();
            user.setCreateBy(SecurityUtils.getUsername());
            String password = configService.selectConfigByKey("sys.user.initPassword");
            user.setPassword(SecurityUtils.encryptPassword(password));
            user.setDeptId(puyuStudent.getDeptId());
            user.setUserName(puyuStudent.getPhone());
            user.setNickName(puyuStudent.getStudentName());
            user.setPhonenumber(puyuStudent.getPhone());
            user.setEmail(puyuStudent.getPhone() + "@ptba.cn");
            user.setSex("0");
            user.setStatus("0");
            user.setDelFlag("0");
            Long[] roleIds = new Long[]{RoleEnum.STUDENT.getRoleId()};
            user.setRoleIds(roleIds);
            userService.insertUser(user);
        }
        puyuStudent.setUserId(user.getUserId());
        puyuStudent.setDeptId(user.getDeptId());

        // 更新队员积分手机号
        PuyuMemberIntegral puyuMemberIntegral = new PuyuMemberIntegral();
        puyuMemberIntegral.setPhone(puyuStudentTemp.getPhone());
        puyuMemberIntegral.setUserId(puyuStudentTemp.getUserId());
        puyuMemberIntegral.setMemberName(puyuStudentTemp.getStudentName());
        List<PuyuMemberIntegral> puyuMemberIntegralList = puyuMemberIntegralMapper.selectPuyuMemberIntegralList(puyuMemberIntegral);
        if (puyuMemberIntegralList.isEmpty()) {
            return;
        }
        PuyuMemberIntegral puyuMemberIntegralTemp = puyuMemberIntegralList.get(0);
        puyuMemberIntegralTemp.setPhone(puyuStudent.getPhone());
        puyuMemberIntegralTemp.setUserId(puyuStudent.getUserId());
        puyuMemberIntegralTemp.setDeptId(puyuStudent.getDeptId());
        puyuMemberIntegralTemp.setMemberName(puyuStudent.getStudentName());
        puyuMemberIntegralTemp.setUpdateBy(SecurityUtils.getUsername());
        puyuMemberIntegralTemp.setUpdateTime(DateUtils.getNowDate());
        puyuMemberIntegralMapper.updatePuyuMemberIntegral(puyuMemberIntegralTemp);

        // 更新积分明细手机号
        PuyuIntegral puyuIntegral = new PuyuIntegral();
        puyuIntegral.setMemberId(puyuMemberIntegralTemp.getMemberId());
        puyuIntegral.setPhone(puyuStudent.getPhone());
        puyuIntegral.setUserId(puyuStudent.getUserId());
        puyuIntegral.setDeptId(puyuStudent.getDeptId());
        puyuIntegral.setMemberName(puyuStudent.getStudentName());
        puyuIntegral.setUpdateBy(SecurityUtils.getUsername());
        puyuIntegral.setUpdateTime(DateUtils.getNowDate());
        puyuIntegralMapper.updatePuyuIntegralByMemberId(puyuIntegral);
    }
}
